package com.mysafe.provision.persistence;

import com.mysafe.provision.util.persistence.EntityManagerLocator;
import com.mysafe.provision.util.persistence.IEMFSingleton;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class DAO<T> implements IDAO<T>, Serializable {
	
	private static final long serialVersionUID = 7196960886563858238L;
	
	private IEMFSingleton emf;

	public DAO(IEMFSingleton emf) {
		this.emf = emf;
	}

	public Integer getIdUser() {
		return EntityManagerLocator.APPLICATION_ENTITY_MANAGER_ID;
	}
	
	public EntityManager getEntityManager() {
		return getEntityManager(EntityManagerLocator.APPLICATION_ENTITY_MANAGER_ID);
	}

	public EntityManager getEntityManager(Integer idUser) {
		EntityManager em = emf.getEntityManagerLocator().get(idUser);
		return em;
	}

	public void persist(Object object) {
		EntityManager em = null;
		EntityTransaction transaction = null;
		try {
			em = getEntityManager(getIdUser());
			transaction = em.getTransaction();
			transaction.begin();
			em.persist(object);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction != null)
				transaction.rollback();
		}
	}

	public void merge(Object object) {
		EntityManager em = null;
		EntityTransaction transaction = null;
		try {
			em = getEntityManager(getIdUser());
			transaction = em.getTransaction();
			transaction.begin();
			em.merge(object);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (transaction != null)
				transaction.rollback();
		}
	}

	public T find() {
		return null;
	}

	public List<T> list() {
		return null;
	}
}